<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./js/vue.js"></script>
</head>
<body>
    <div id="app">
        <ul>
            <li v-for="(p, index) in products" :key="index">
                <p>产品名称：{{p.name}}</p>
                <p>发布时间：{{p.date}}</p>
                <!-- <p>发布时间: {{p.date|firstFilters("haha")}}</p>
                <p>发布时间: {{p.date|firstFilters(1,2,3,4)}}</p> -->
                <p>发布时间：{{p.date | formData('yyyy-MM-dd hh:mm:ss')}}</p>
            </li>
        </ul>
    </div>
</body>
<script>
    new Vue({
        el:"#app",
        data:{
            products:[
                {name:"产品1",date:new Date("2018-12-20 13:35:42")},
                {name:"产品1",date:new Date("2018-3-13 8:35:42")},
                {name:"产品1",date:new Date("2019-4-20 15:35:42")},
                {name:"产品1",date:new Date("2019-10-20 20:35:42")}
            ]
        },
        computed: {
            
        },
        filters:{
            firstFilters(target,...arg){
                console.log(arg,this);
                return target+":"+arg;
            },
            formData(target,str){
                if(!(target instanceof Date)){
                    console.warn("formatDate是对时间对象进行格式化的方法");
                }
                let y = target.getFullYear()+"";

                let o = {
                    "(M+)":target.getMonth()+1+"",
                    "(d+)":target.getDate()+"",
                    "(h+)":target.getHours()+"",
                    "(m+)":target.getMinutes()+"",
                    "(s+)":target.getSeconds()+""
                }  

                if(new RegExp("(y+)").test(str)){
                    // RegExp.$1表示紧接着上一次替换掉的所有字符
                    str=str.replace(/y+/,y.substr(4-RegExp.$1.length,RegExp.$1.length));
                }

                for (const key in o) {
                   let reg = new RegExp(key);
                   if(reg.test(str)){
                       let rep="";
                       //如果要替换的长度是1
                       if(RegExp.$1.length==1){
                            rep=o[key];
                       //如果要替换的长度是2
                        // 1,2,3  11 12  ==>  01 02 03  011 012  再截取后两位
                       }else{
                           rep=("0"+o[key]).substr(-2,2);
                       }
                       str=str.replace(reg,rep);
                   } 

                   
                }
                return str;
            }
        }
        
    });
</script>
</html>